package net.yxsoft.kit;

import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import rapid.core.ContextStateEnum;
import rapid.core.ExceptionDescriptor;
import rapid.core.TResult;

import java.sql.SQLException;
import java.util.List;

/**
 * @ClassName: CustomDb
 * @Description: 数据存储处理
 * @author: wj
 * @date: 2023/11/14 9:08
 */


public class CustomDb extends Db {
   private static TResult result=new TResult();
   /**
   * @MethodName: saveWithExceptionHandling
   * @Description: 保存
   * @param: tableName
    * @param: record
   * @return void
   * @throws
   * @date 2023/11/14 9:57
   * @author wj
   */
    public static TResult saveWithExceptionHandling(String tableName, Record record) {

        try {
           Boolean isSuccess= Db.save(tableName, record);
            result.setData(isSuccess);
            result.setState(ContextStateEnum.SUCCESS);
            result.setMessage(null);
        } catch (Exception e) {
            result= setError(e);
        }
        return result;
    }
    /**
     * @MethodName: saveWithExceptionHandling
     * @Description: 保存
     * @param: tableName
     * @param: record
     * @return void
     * @throws
     * @date 2023/11/14 9:57
     * @author wj
     */
    public static TResult saveWithExceptionHandling(String tableName, String primaryKey, Record record) {
        try {
            Boolean isSuccess= Db.save(tableName, primaryKey,record);
            result.setData(isSuccess);
            result.setState(ContextStateEnum.SUCCESS);
            result.setMessage(null);
        } catch (Exception e) {
            result= setError(e);
        }
        return result;
    }


    /**
     * @MethodName: saveWithExceptionHandling
     * @Description: 更新
     * @param: tableName
     * @param: record
     * @return void
     * @throws
     * @date 2023/11/14 9:57
     * @author wj
     */
    public static TResult updateWithExceptionHandling(String tableName, Record record) {
        try {
            Boolean isSuccess= Db.update(tableName, record);
            result.setData(isSuccess);
            result.setState(ContextStateEnum.SUCCESS);
            result.setMessage(null);
        } catch (Exception e) {
            result= setError(e);
        }
        return result;
    }
    /**
     * @MethodName: saveWithExceptionHandling
     * @Description: 更新
     * @param: tableName
     * @param: record
     * @return void
     * @throws
     * @date 2023/11/14 9:57
     * @author wj
     */
    public static TResult updateWithExceptionHandling(String tableName, String primaryKey, Record record) {
        try {
            Boolean isSuccess= Db.update(tableName,primaryKey, record);
            result.setData(isSuccess);
            result.setState(ContextStateEnum.SUCCESS);
            result.setMessage(null);
        } catch (Exception e) {
            result= setError(e);
        }
        return result;
    }


    /**
     * @MethodName: saveWithExceptionHandling
     * @Description: 更新
     * @param: tableName
     * @param: record
     * @return void
     * @throws
     * @date 2023/11/14 9:57
     * @author wj
     */
    public static TResult updateWithExceptionHandling(String sql, Object... paras) {
        try {
            int updSize= Db.update(sql,paras);
            result.setData(updSize);
            result.setState(ContextStateEnum.SUCCESS);
            result.setMessage(null);
        } catch (Exception e) {
            result= setError(e);
        }
        if(result.isFail()){
            result.setData(0);
        }
        return result;
    }


    /**
     * @MethodName: saveWithExceptionHandling
     * @Description: 更新
     * @param: tableName
     * @param: record
     * @return void
     * @throws
     * @date 2023/11/14 9:57
     * @author wj
     */
    public static TResult updateWithExceptionHandling(String sql) {
        try {
            int updSize= Db.update(sql);
            result.setData(updSize);
            result.setState(ContextStateEnum.SUCCESS);
            result.setMessage(null);
        } catch (Exception e) {
            result= setError(e);
        }
        if(result.isFail()){
            result.setData(0);
        }
        return result;
    }

    /**
     * @MethodName: saveWithExceptionHandling
     * @Description: 查询结果集
     * @param: tableName
     * @param: record
     * @return void
     * @throws
     * @date 2023/11/14 9:57
     * @author wj
     */
    public static TResult findWithExceptionHandling(String sql) {
        try {
            List<Record> reRecords= Db.find(sql);
            result.setData(reRecords);
            result.setState(ContextStateEnum.SUCCESS);
            result.setMessage(null);
        } catch (Exception e) {
            result= setError(e);
        }
        return result;
    }
    /**
     * @MethodName: saveWithExceptionHandling
     * @Description: 查询结果集
     * @param: tableName
     * @param: record
     * @return void
     * @throws
     * @date 2023/11/14 9:57
     * @author wj
     */
    public static TResult findWithExceptionHandling(String sql, Object... paras) {
        try {
            List<Record> reRecords= Db.find(sql,paras);
            result.setData(reRecords);
            result.setState(ContextStateEnum.SUCCESS);
            result.setMessage(null);
        } catch (Exception e) {
            result= setError(e);
        }
        return result;
    }
    /**
     * @MethodName: saveWithExceptionHandling
     * @Description: 查询一个结果
     * @param: tableName
     * @param: record
     * @return void
     * @throws
     * @date 2023/11/14 9:57
     * @author wj
     */
    public static TResult findFirstWithExceptionHandling(String sql) {
        try {
            Record reRecord=  Db.findFirst(sql);
            result.setData(reRecord);
            result.setState(ContextStateEnum.SUCCESS);
            result.setMessage(null);
        } catch (Exception e) {
            result= setError(e);
        }
        return result;
    }
    /**
     * @MethodName: saveWithExceptionHandling
     * @Description: 查询一个结果
     * @param: tableName
     * @param: record
     * @return void
     * @throws
     * @date 2023/11/14 9:57
     * @author wj
     */
    public static TResult findFirstWithExceptionHandling(String sql, Object... paras) {
        try {
            Record reRecord= Db.findFirst(sql, paras);
            
            result.setData(reRecord);
            result.setState(ContextStateEnum.SUCCESS);
            result.setMessage(null);
        } catch (Exception e) {
            result= setError(e);
        }
        return result;
    }
    /**
     * @MethodName: saveWithExceptionHandling
     * @Description: 根据主键查询一个结果
     * @param: tableName
     * @param: record
     * @return void
     * @throws
     * @date 2023/11/14 9:57
     * @author wj
     */
    public static TResult findByIdWithExceptionHandling(String tableName, Record record) {
        try {
            Record reRecord= Db.findById(tableName, record);
            result.setData(reRecord);
            result.setState(ContextStateEnum.SUCCESS);
            result.setMessage(null);
        } catch (Exception e) {
            result= setError(e);
        }
        return result;
    }
    /**
     * @MethodName: saveWithExceptionHandling
     * @Description: 根据主键查询一个结果
     * @param: tableName
     * @param: record
     * @return void
     * @throws
     * @date 2023/11/14 9:57
     * @author wj
     */
    public static TResult findByIdWithExceptionHandling(String tableName, String primaryKey, Object idValue) {
        try {
            Record reRecord=Db.findById(tableName,primaryKey, idValue);
            result.setData(reRecord);
            result.setState(ContextStateEnum.SUCCESS);
            result.setMessage(null);
        } catch (Exception e) {
            result= setError(e);
        }
        return result;
    }

    /**
    * @MethodName: setError
    * @Description: 错误信息收集
    * @param: e
    * @return void
    * @throws
    * @date 2023/11/14 9:59
    * @author wj
    */
    private static TResult setError(Exception e){
        if (e instanceof ActiveRecordException) {
            ActiveRecordException activeRecordException = (ActiveRecordException) e;
            Throwable cause = activeRecordException.getCause();

            // 判断异常类型并进行处理
            if (cause instanceof SQLException) {
                SQLException sqlException = (SQLException) cause;
                int errorCode = sqlException.getErrorCode();
                String sqlState = sqlException.getSQLState();
                // 判断异常类型并进行处理
                if (errorCode == 1040 ) {
                    // SQL 语句格式错误异常处理
                    return  handleError("当前连接到数据库的连接数超过了数据库允许的最大连接数。" , e);
                }else if (errorCode == 1042 ) {
                    // SQL 语句格式错误异常处理
                    return  handleError("表示无法连接到指定的 MySQL 主机。" , e);
                }else if (errorCode == 1045 ) {
                    // SQL 语句格式错误异常处理
                    return  handleError("表示数据库连接时使用的用户名或密码不正确。" , e);
                }else if (errorCode == 1406) {
                    // 字段超出长度异常处理
                    String columnName = getColumnNameFromError(sqlException.getMessage());
                    return  handleError("字段超出长度错误，字段名：" + columnName, e);
                }else if (errorCode == 1364) {
                    // 字段超出长度异常处理
                    String columnName = getColumnNameFromError(sqlException.getMessage());
                    return  handleError("未为非空字段提供默认值，字段名：" + columnName, e);
                }else if (errorCode == 1451) {
                    // 字段超出长度异常处理
                    return  handleError("违反了外键约束，修改或删除的行被其他表的外键引用。" , e);
                } else if (errorCode == 2013) {
                    // 字段超出长度异常处理
                    return  handleError("在执行查询过程中失去了与 MySQL 服务器的连接。" , e);
                }   else if (errorCode == 1366) {
                    // 数据类型转换错误异常处理
                    return handleError("数据类型转换错误", e);
                } else if (errorCode == 1064) {
                    // SQL 语句格式错误异常处理
                    return  handleError("SQL 语句格式错误", e);
                } else if (errorCode == 1054 ) {
                    // SQL 语句格式错误异常处理
                    String columnName = getColumnNameFromError(sqlException.getMessage());
                    return  handleError("字段不存在，字段名：" + columnName, e);
                } else if (errorCode == 0) {
                    // SQL 语句格式错误异常处理
                    return  handleError("SQL 语句格式错误", e);
                }
            }
        }

        // 其他异常类型，进行处理
       return handleError("未处理的异常：" + e.getMessage(), e);
    }

    private static String getColumnNameFromError(String errorMessage) {
        // 解析错误信息，获取字段名
        String columnName = errorMessage.split("'")[1];
        return columnName;
    }

    /**
    * @MethodName: handleError
    * @Description: 错误信息返回
    * @param: errorMessage
     * @param: e
    * @return rapid.core.TResult
    * @throws
    * @date 2023/11/14 10:00
    * @author wj
    */
    private static TResult handleError(String errorMessage, Exception e) {
        result.setState(ContextStateEnum.FAIL);
        result.setMessage(errorMessage);
        result.setException(new ExceptionDescriptor(e));
        return result;
    }
}